﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Voodoo.SharePoint.ReadUnreadMarks;

namespace Voodoo.SharePoint.ReadUnreadMarks
{
    public partial class LazyReadUnreadUpdate : LayoutsPageBase
    {
         //This page responds to the inline editor, it could have been a nice
        //elegant Ajax or SOAP call but I did it this way , 6 of one 1/2 dozen
        //of the other. The page returns simple text as to the new status of 
        //the row, read, unread or error
        //the requested value is the value of the check box which is checked
        //if the item has been read, unchecked if it has not been read
        //which means on a transition you get a false for unchecked which means
        //set the item to unread. or a true for checked which means set the item
        //as read
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Web.HttpContext.Current.Response.CacheControl = "no-cache";
            System.Web.HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
            System.Web.HttpContext.Current.Response.Expires = -1;

            string itemIDQS = Request.QueryString["iID"];
            string listIDQS = Request.QueryString["lID"];
            string newValueQS = Request.QueryString["nValue"];
            string propertyName = Request.QueryString["pName"];
            string returnValue = "unknown";
            bool writeDirect = UtilityMethods.WriteDirect();

            try
            {
                if (!string.IsNullOrEmpty(newValueQS))
                {
                    bool setReadMark = bool.Parse(newValueQS);
                    
                    int itemId = int.Parse(itemIDQS);
                    Guid listId = new Guid(listIDQS);
                    Guid siteId = SPContext.Current.Web.Site.ID;
                    Guid webId = SPContext.Current.Web.ID;
                  
                    string authUserName = System.Web.HttpContext.Current.User.Identity.Name;
                    if (authUserName.IndexOf('|') > -1)
                    {
                        string[] nameParts = authUserName.Split('|');
                        authUserName = nameParts[nameParts.GetUpperBound(0)];
                    }
                    SPUser currentUser = null;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite currrentSite = new SPSite(siteId))
                        {
                            using (SPWeb currentWeb = currrentSite.OpenWeb(webId))
                            {
                                bool currentUnsafeSetting = currentWeb.AllowUnsafeUpdates;
                                currentWeb.AllowUnsafeUpdates = true;
                                currentUser = currentWeb.EnsureUser(authUserName);
                                try
                                {
                                    SPList targetList = currentWeb.Lists[listId];
                                    SPListItem targetItem = targetList.GetItemById(itemId);
                                    ReadUnreadField sharePointField = (ReadUnreadField)targetList.Fields.GetFieldByInternalName(propertyName);
                                    if (setReadMark)
                                    {
                                        UtilityMethods.MarkItemAsRead(currentUser, targetItem, sharePointField);
                                        returnValue = "read";
                                    }
                                    else
                                    {
                                        UtilityMethods.MarkItemAsUnread(currentUser, targetItem, sharePointField);
                                        returnValue = "unread";
                                    }
                                }
                                finally
                                {
                                    currentWeb.AllowUnsafeUpdates = currentUnsafeSetting;
                                }
                            }
                        }
                    });
                }
            }
            catch (Exception innerErr)
            {
                System.Diagnostics.Trace.WriteLine(innerErr.Message);
                returnValue = "error";
                //Response.Write(innerErr.Message);
                //Response.Write("<hr>");
                //Response.Write(System.Web.HttpContext.Current.Request.Url.ToString());
                //Response.Write("<hr>");
                //Response.Write(innerErr.StackTrace.Replace("\n", "<BR>"));

            }
            System.Web.HttpContext.Current.Response.Write(returnValue);
            System.Web.HttpContext.Current.Response.End();
        }
    }
}
